<?php
/**
 * LoginController.php
 *
 * @copyright  2022 beikeshop.com - All Rights Reserved
 * @link       https://beikeshop.com
 * @author     TL <mengwb@guangda.work>
 * @created    2022-06-22 20:22:54
 * @modified   2022-06-22 20:22:54
 */

namespace Beike\Seller\Http\Controllers;

use Beike\Seller\Http\Requests\LoginRequest;
use Beike\Seller\Models\SellerUser;
use function current_seller_user;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    /**
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function index()
    {
        if (current_seller_user()) {
            return redirect(seller_route('home.index'));
        }

        return view('seller::login');
    }

    /**
     * @param LoginRequest $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(LoginRequest $request)
    {
        if (! auth(SellerUser::AUTH_GUARD)->attempt($request->only('email', 'password'))) {
            return redirect()->back()->with(['error' => trans('auth.failed')])->withInput();
        }

        $user = current_seller_user();
        if ($user && $user->status != 1) {
            Auth::guard(SellerUser::AUTH_GUARD)->logout();

            return redirect()->back()->with(['error' => trans('seller::login.user_inactive')])->withInput();
        } elseif($user->seller->status != 1) {
            Auth::guard(SellerUser::AUTH_GUARD)->logout();

            return redirect()->back()->with(['error' => trans('seller::login.seller_inactive')])->withInput();
        }

        return redirect(seller_route('home.index'));
    }
}
